﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Globalization;
using System.Reflection;

namespace Hired
{
    public partial class jsprofile : System.Web.UI.Page
    {
        private JobseekerAccount js;

        protected void Page_Init(object sender, EventArgs e)
        {
            if (User.IsInRole("jobseeker"))
            {
                js = DBJobseekerAccount.retrieveJobseekerAccount(User.Identity.Name, true);
                lblUsername.Text = (string)Session["username"];
                edsImages.WhereParameters[0].DefaultValue = User.Identity.Name;
            }
            else
            {
                Response.Redirect("home.aspx");
            }

            //Wall Thread
            List<Thread> wallThread = DBThread.RetrieveThreadsByUserID(js.JAccountID);

            if (wallThread.Count != 0)
            {
                foreach (Thread t in wallThread)
                {
                    #region Thread
                    UCComments tc = (UCComments)LoadControl("UCComments.ascx");
                    pnlContainer.Controls.Add(tc);

                    // accessing ThreadComment.ascx controls
                    Image threadImgProfilePic = (Image)tc.FindControl("imgProfilePic");
                    Label threadLblCommentContent = (Label)tc.FindControl("lblCommentContent");
                    LinkButton threadBtnUsername = (LinkButton)tc.FindControl("btnUsername");

                    // assigning values to them
                    if (DBJobseekerAccount.retrieveJobseekerAccount(t.PosterID, true) != null)
                    {
                        JobseekerAccount jsPoster = DBJobseekerAccount.retrieveJobseekerAccount(t.PosterID, true);
                        threadImgProfilePic.ImageUrl = jsPoster.Jobseeker.ImageAddress;
                        threadBtnUsername.Text = jsPoster.Username;
                        threadBtnUsername.PostBackUrl = "viewprofile.aspx?username=" + jsPoster.Username;
                    }
                    else if (DBCompanyAccount.RetrieveCompanyAccount(t.PosterID, true) != null)
                    {
                        CompanyAccount coPoster = DBCompanyAccount.RetrieveCompanyAccount(t.PosterID, true);
                        threadImgProfilePic.ImageUrl = coPoster.Company.ImageAddress;
                        threadBtnUsername.Text = coPoster.Username;
                        threadBtnUsername.PostBackUrl = "viewprofile.aspx?username=" + coPoster.Username;
                    }
                    threadLblCommentContent.Text = t.Contents;

                    #endregion

                    #region Comments
                    if (t.Comments.Count != 0)
                    {
                        foreach (Comment c in t.Comments)
                        {
                            UCComments comment = (UCComments)Page.LoadControl("UCComments.ascx");
                            pnlContainer.Controls.Add(comment);

                            // accessing ThreadUC.ascx controls
                            Panel commentPnlComment = (Panel)comment.FindControl("pnlComment");
                            Image commentImgProfilePic = (Image)comment.FindControl("imgProfilePic");
                            Label commentLblCommentContent = (Label)comment.FindControl("lblCommentContent");
                            LinkButton commentBtnUsername = (LinkButton)comment.FindControl("btnUsername");

                            // assigning values to them
                            commentPnlComment.CssClass = "pnlComment";
                            if (DBJobseekerAccount.retrieveJobseekerAccount(t.PosterID, true) != null)
                            {
                                JobseekerAccount jsPoster = DBJobseekerAccount.retrieveJobseekerAccount(t.PosterID, true);
                                commentImgProfilePic.ImageUrl = jsPoster.Jobseeker.ImageAddress;
                                commentBtnUsername.Text = jsPoster.Username;
                                commentBtnUsername.PostBackUrl = "viewprofile.aspx?username=" + jsPoster.Username;
                            }
                            else if (DBCompanyAccount.RetrieveCompanyAccount(t.PosterID, true) != null)
                            {
                                CompanyAccount coPoster = DBCompanyAccount.RetrieveCompanyAccount(t.PosterID, true);
                                commentImgProfilePic.ImageUrl = coPoster.Company.ImageAddress;
                                commentBtnUsername.Text = coPoster.Username;
                                commentBtnUsername.PostBackUrl = "viewprofile.aspx?username=" + coPoster.Username;
                            }
                            commentLblCommentContent.Text = c.Contents;
                        }
                    }
                    #endregion

                    UCPostComment pc = (UCPostComment)Page.LoadControl("UCPostComment.ascx");
                    ((Label)pc.FindControl("lblThreadID")).Text = t.ThreadID;
                    pnlContainer.Controls.Add(pc);

                    Button btnPost = (Button)pc.FindControl("btnPost");
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }


        protected void btnWall_Click(object sender, ImageClickEventArgs e)
        {
            hidePanels();           // hides all panels on the page
            pnlWall.Visible = true; // sets one panel to visible
        }

        protected void btnInformation_Click(object sender, ImageClickEventArgs e)
        {
            hidePanels();
            pnlPersonalInformation.Visible = true;

            #region Initializing values for display
            lblFirstNameValue.Text = js.Jobseeker.FirstName;
            lblLastNameValue.Text = js.Jobseeker.LastName;
            switch (js.Jobseeker.Gender)
            {
                case "M":
                    lblGenderValue.Text = "Male";
                    break;
                case "F":
                    lblGenderValue.Text = "Female";
                    break;
            }
            lblDateOfBirthValue.Text = js.Jobseeker.DateOfBirth.Value.ToLongDateString();
            lblNationalityValue.Text = js.Jobseeker.Nationality;
            lblCountryOfResidenceValue.Text = js.Jobseeker.CountryOfResidence;
            lblAddressValue.Text = js.Jobseeker.Address;
            lblPostalCodeValue.Text = js.Jobseeker.PostalCode;
            if (js.Jobseeker.WebsiteURL != null && js.Jobseeker.WebsiteURL != "")
            {
                lblWebsiteValue.Text = js.Jobseeker.WebsiteURL;
            }
            else
            {
                lblWebsite.Visible = false;
                lblWebsiteValue.Visible = false;
            }

            lblEmailValue.Text = js.Email;
            if (js.Jobseeker.HomeNumber != null && js.Jobseeker.HomeNumber != "")
            {
                lblHomeNumberValue.Text = js.Jobseeker.HomeNumber + "<br /><br />";
            }
            else
            {
                lblHomeNumber.Visible = false;
                lblHomeNumberValue.Visible = false;
            }
            if (js.Jobseeker.MobileNumber != null && js.Jobseeker.MobileNumber != "")
            {
                lblMobileNumberValue.Text = js.Jobseeker.MobileNumber;
            }
            else
            {
                lblMobileNumber.Visible = false;
                lblMobileNumberValue.Visible = false;
            }

            lblEducationLevelValue.Text = js.Jobseeker.EducationLevel;
            if (js.Jobseeker.PreviousEducationalInstitute != null && js.Jobseeker.PreviousEducationalInstitute != "")
            {
                lblPreviousEducationalInstituteValue.Text = js.Jobseeker.PreviousEducationalInstitute + "<br /><br />";
            }
            else
            {
                lblPreviousEducationalInstitute.Visible = false;
                lblPreviousEducationalInstituteValue.Visible = false;
            }
            if (js.Jobseeker.Specialization != null && js.Jobseeker.Specialization != "")
            {
                lblSpecializationValue.Text = js.Jobseeker.Specialization + "<br /><br />";
            }
            else
            {
                lblSpecialization.Visible = false;
                lblSpecializationValue.Visible = false;
            }
            if (js.Jobseeker.PreviousEmployment != null && js.Jobseeker.PreviousEmployment != "")
            {
                lblPreviousEmploymentValue.Text = js.Jobseeker.PreviousEmployment + "<br /><br />";
            }
            else
            {
                lblPreviousEmployment.Visible = false;
                lblPreviousEmploymentValue.Visible = false;
            }
            if (js.Jobseeker.CurrentEmployment != null && js.Jobseeker.PreviousEmployment != "")
            {
                lblCurrentEmploymentValue.Text = js.Jobseeker.CurrentEmployment;
            }
            else
            {
                lblCurrentEmployment.Visible = false;
                lblCurrentEmploymentValue.Visible = false;
            }
            #endregion
        }

        protected void lblUpdateInfo_Click(object sender, EventArgs e)
        {
            hidePanels();
            pnlUpdateInformation.Visible = true;

            #region Initializing values in TextBoxes
            txtFirstName.Text = js.Jobseeker.FirstName;
            txtLastName.Text = js.Jobseeker.LastName;
            switch (js.Jobseeker.Gender)
            {
                case "M":
                    ddlGender.SelectedIndex = 0;
                    break;
                case "F":
                    ddlGender.SelectedIndex = 1;
                    break;
            }
            txtDateOfBirth.Text = js.Jobseeker.DateOfBirth.Value.ToLongDateString().Replace('/', '-');
            txtNationality.Text = js.Jobseeker.Nationality;
            #region loading countries from countries.xml
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("countries.xml"));

            foreach (XmlNode node in doc.SelectNodes("//country"))
            {
                ddlCountryOfResidence.Items.Add(new ListItem(node.InnerText));
            }
            #endregion
            ddlCountryOfResidence.Text = js.Jobseeker.CountryOfResidence;
            txtAddress.Text = js.Jobseeker.Address;
            txtPostalCode.Text = js.Jobseeker.PostalCode;
            txtWebsiteURL.Text = js.Jobseeker.WebsiteURL;

            lblUpdateEmail.Text = js.Email;
            txtHomeNumber.Text = js.Jobseeker.HomeNumber;
            txtMobileNumber.Text = js.Jobseeker.MobileNumber;

            ddlEducationLevel.Text = js.Jobseeker.EducationLevel;
            txtPreviousEducationalInstitute.Text = js.Jobseeker.PreviousEducationalInstitute;
            ddlSpecialization.Text = js.Jobseeker.Specialization;
            txtPreviousEmployment.Text = js.Jobseeker.PreviousEmployment;
            txtCurrentEmployment.Text = js.Jobseeker.CurrentEmployment;
            #endregion
        }

        protected void btnComment_Click(object sender, EventArgs e)
        {
            Thread t = new Thread();
            t.Contents = txtComment.Text;
            t.PosterID = User.Identity.Name;
            t.WallID = js.JAccountID;

            DBThread.AddThread(t);
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                #region Retrieving values from input fields
                js.Jobseeker.FirstName = txtFirstName.Text;
                js.Jobseeker.LastName = txtLastName.Text;
                switch (ddlGender.SelectedIndex)
                {
                    case 0:
                        js.Jobseeker.Gender = "M";
                        break;
                    case 1:
                        js.Jobseeker.Gender = "F";
                        break;
                }
                CultureInfo ci = new CultureInfo("es-ES");
                js.Jobseeker.DateOfBirth = DateTime.Parse(txtDateOfBirth.Text, ci);
                js.Jobseeker.Nationality = txtNationality.Text;
                js.Jobseeker.CountryOfResidence = ddlCountryOfResidence.Text;
                js.Jobseeker.Address = txtAddress.Text;
                js.Jobseeker.PostalCode = txtPostalCode.Text;
                js.Jobseeker.WebsiteURL = txtWebsiteURL.Text;

                js.Jobseeker.HomeNumber = txtHomeNumber.Text;
                js.Jobseeker.MobileNumber = txtMobileNumber.Text;

                js.Jobseeker.EducationLevel = ddlEducationLevel.Text;
                js.Jobseeker.PreviousEducationalInstitute = txtPreviousEducationalInstitute.Text;
                js.Jobseeker.Specialization = ddlSpecialization.Text;
                js.Jobseeker.PreviousEmployment = txtPreviousEmployment.Text;
                js.Jobseeker.CurrentEmployment = txtCurrentEmployment.Text;
                #endregion

                DBJobseekerAccount.updateJobseekerAccount(js);
                DBJobseeker.UpdateJobseeker(js.Jobseeker);
                hidePanels();
                pnlWall.Visible = true;
            }
        }

        protected void btnBuddyList_Click(object sender, ImageClickEventArgs e)
        {
            hidePanels();
            pnlBuddyList.Visible = true;

            lvBuddyList.DataSource = DBBuddyRoster.viewBuddyImageNameList(User.Identity.Name);
            lvBuddyList.DataBind();
        }

        protected void lblBuddyRequest_Click(object sender, EventArgs e)
        {
            hidePanels();
            pnlBuddyRequests.Visible = true;

            gvBuddyRequests.DataSource = DBBuddyRequestRoster.retrieveBuddyRequestListForDisplay(User.Identity.Name);
            gvBuddyRequests.DataBind();
        }

        protected void btnImages_Click(object sender, ImageClickEventArgs e)
        {
            hidePanels();
            pnlImages.Visible = true;
        }

        protected void btnInbox_Click(object sender, ImageClickEventArgs e)
        {
            hidePanels();
            pnlInbox.Visible = true;

            gvInbox.DataSource = DBMessage.retrieveInbox(User.Identity.Name);
            gvInbox.DataBind();
        }

        protected void CustomDOB_ServerValidate(object source, ServerValidateEventArgs args)
        {
            string stringDOB = txtDateOfBirth.Text;
            CultureInfo ci = new CultureInfo("es-ES");
            DateTime inputDOB = DateTime.Parse(stringDOB, ci);

            DateTime now = DateTime.Today;
            int age = now.Year - inputDOB.Year;

            if (inputDOB > now.AddYears(-age))
            {
                age--;
            }
            DateTime d = DateTime.Now;
            if (age >= 16)
            {
                // user is 16 years old and above
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }

        protected void hidePanels()
        {
            pnlWall.Visible = false;
            pnlPersonalInformation.Visible = false;
            pnlUpdateInformation.Visible = false;
            pnlBuddyList.Visible = false;
            pnlBuddyRequests.Visible = false;
            pnlImages.Visible = false;
            pnlInbox.Visible = false;
        }

        protected void linkBtnViewAll_Click(object sender, EventArgs e)
        {
            Response.Redirect("viewWatchList.aspx");
        }

        protected void gvInbox_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Select":
                    pnlMessage.Visible = true;

                    try
                    {
                        Message m = DBMessage.RetrieveMessage((string)e.CommandArgument);
                        GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

                        switch (DBAccount.RetrieveAccountTypeByID(m.SenderID))
                        {
                            case "CompanyAccount":
                                CompanyAccount ca = DBCompanyAccount.RetrieveCompanyAccount(m.SenderID, false);
                                lblMessageSender.Text = ca.Username;
                                break;
                            case "JobseekerAccount":
                                JobseekerAccount jsa = DBJobseekerAccount.retrieveJobseekerAccount(m.SenderID, false);
                                lblMessageSender.Text = jsa.Username;
                                break;
                        }
                        lblMessageTitle.Text = m.Title;
                        lblMessageContents.Text = m.Contents;
                    }
                    catch (Exception)
                    {
                        lblMessageSender.Text = "N/A";
                        lblMessageTitle.Text = "N/A";
                        lblMessageContents.Text = "Message does not exist!";
                    }
                    break;
                case "Delete":
                    DBMessage.DeleteMessagebyId((string)e.CommandArgument);
                    break;
            }
        }

        protected void lvBuddyRequests_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            if (e.Exception != null)
            {
                if (e.AffectedRows == 0)
                {
                    e.KeepInInsertMode = true;
                    Console.WriteLine("An exception occurred inserting the new UserID. " +
                      "Please verify your values and try again.");
                }
                else
                    Console.WriteLine("An exception occurred inserting the new UserID. " +
                      "Please verify the values in the newly inserted item.");

                e.ExceptionHandled = true;
            }

            BuddyRoster br = new BuddyRoster();
            //br.BuddyID1 = BuddyIDLabel;
            br.BuddyID2 = User.Identity.Name;
        }

        protected void gvBuddyRequests_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Accept":
                    BuddyRoster br = new BuddyRoster();
                    br.BuddyID1 = (string)e.CommandArgument;
                    br.BuddyID2 = User.Identity.Name;

                    DBBuddyRequestRoster.deleteBuddyRequest((string)e.CommandArgument, User.Identity.Name);
                    DBBuddyRoster.addBuddy(br);

                    gvBuddyRequests.DataSource = DBBuddyRequestRoster.retrieveBuddyRequestListForDisplay(User.Identity.Name);
                    gvBuddyRequests.DataBind();
                    break;
                case "Decline":
                    DBBuddyRequestRoster.deleteBuddyRequest((string)e.CommandArgument, User.Identity.Name);
                    break;
            }
        }
    }
}
